package uk.ac.open.kmi.dyniqx.repositories;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.lucene.document.Field;
import org.directwebremoting.WebContext;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

import uk.ac.open.kmi.dyniqx.storages.Storage;

public class YahooImagesThread extends Thread {
	
	public String queryString;
	public int count;

	public Storage storage;
	public WebContext wctx;
	
	public volatile boolean stop = false;
	
	public Logger logger = Logger.getLogger("uk.ac.open.kmi.dyniqx.repositories.YahooImagesThread");
	
	public YahooImagesThread(Storage storage, WebContext wctx, String queryString, int count) {
		
		this.setStorage(storage);
		this.setWctx(wctx);
		this.setQueryString(queryString);
		this.setCount(count);
		
	}
	
	@SuppressWarnings("unchecked")
	public void run() {
		
		this.logger.debug("Thread started.");
		
		SAXBuilder parser = new SAXBuilder();
		String searchUrl = "http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=SoE1x_TV34HSVv56Bm7BuXyT4wFLqNoVKy7OvZVOFEyry6JMENE4jIspIV5TcHSj&query=" + this.getQueryString();
		if (this.count > 20) this.count = 20;
		int startIndex = 1;
		int max = 20;
		int temp_count = 0;
		Document doc;
		
		/* Open University proxy Settings */

		System.getProperties().put( "proxySet", "true" );
		System.getProperties().put( "proxyHost", "wwwcache" );
		System.getProperties().put( "proxyPort", "80" );
		System.setProperty("java.net.useSystemProxies","true");
		
		try {
			
			while ((startIndex <= this.count) && !stop) {
				
				temp_count = 0;
				doc = parser.build(searchUrl + "&results=" + max + "&start=" + startIndex);
				
				XPath x = XPath.newInstance("/nms:ResultSet/nms:Result");
				x.addNamespace("nms", "urn:yahoo:srchmi");
					
				List<Element> list = (List<Element>) x.selectNodes(doc);
			    Iterator iterator = list.iterator();
			    
			    org.apache.lucene.document.Document result = null;
			    ArrayList<org.apache.lucene.document.Document> documentArray = new ArrayList<org.apache.lucene.document.Document>();
			    
			    while (iterator.hasNext()) {
			        Element el = (Element) iterator.next();
			        
			        x = XPath.newInstance("nms:Title");
			        x.addNamespace("nms", "urn:yahoo:srchmi");
			        String id = x.valueOf(el);

			        x = XPath.newInstance("nms:Summary");
			        x.addNamespace("nms", "urn:yahoo:srchmi");
			        String summary = x.valueOf(el);
			        if (summary.equals("")) summary = "n/a";
			        
			        x = XPath.newInstance("nms:Url");
			        x.addNamespace("nms", "urn:yahoo:srchmi");
			        String url = x.valueOf(el);

			        x = XPath.newInstance("nms:RefererUrl");
			        x.addNamespace("nms", "urn:yahoo:srchmi");
			        String refererUrl = x.valueOf(el);
			        
			        x = XPath.newInstance("nms:FileSize");
			        x.addNamespace("nms", "urn:yahoo:srchmi");
			        String fileSize = x.valueOf(el);
			        if (fileSize.equals("")) fileSize = "n/a";
			        
			        x = XPath.newInstance("nms:FileFormat");
			        x.addNamespace("nms", "urn:yahoo:srchmi");
			        String fileFormat = x.valueOf(el);
			        if (fileFormat.equals("")) fileFormat = "n/a";
			        
			        x = XPath.newInstance("nms:Width");
			        x.addNamespace("nms", "urn:yahoo:srchmi");
			        String width = x.valueOf(el);
			        
			        x = XPath.newInstance("nms:Height");
			        x.addNamespace("nms", "urn:yahoo:srchmi");
			        String height = x.valueOf(el);
			        
			        x = XPath.newInstance("nms:Thumbnail/nms:Url");
			        x.addNamespace("nms", "urn:yahoo:srchmi");
			        String thumbUrl = x.valueOf(el);

			        x = XPath.newInstance("nms:Thumbnail/nms:Width");
			        x.addNamespace("nms", "urn:yahoo:srchmi");
			        String thumbWidth = x.valueOf(el);
			        
			        x = XPath.newInstance("nms:Thumbnail/nms:Height");
			        x.addNamespace("nms", "urn:yahoo:srchmi");
			        String thumbHeight = x.valueOf(el);
		        
			        result = new org.apache.lucene.document.Document();

			        result.add(new Field("source", "YIm", Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("type", "image", Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("id", id, Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("query", queryString, Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("rank", Integer.toString(temp_count + startIndex), Field.Store.YES, Field.Index.UN_TOKENIZED));
			        
			        result.add(new Field("link", url, Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("internal", refererUrl, Field.Store.YES, Field.Index.UN_TOKENIZED));
			        
			        result.add(new Field("summary", summary, Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.YES));
			        result.add(new Field("width", width, Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("height", height, Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("fileSize", fileSize, Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("fileFormat", fileFormat, Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("thumbUrl", thumbUrl, Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("thumbWidth", thumbWidth, Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("thumbHeight", thumbHeight, Field.Store.YES, Field.Index.UN_TOKENIZED));
			        
			        result.add(new Field("title", "n/a", Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("description", "n/a", Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("date", "n/a", Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("authors", "n/a", Field.Store.YES, Field.Index.UN_TOKENIZED));
			        result.add(new Field("journal", "n/a", Field.Store.YES, Field.Index.UN_TOKENIZED));
			        
			        result.setBoost(500 / ++temp_count);
			        
			        documentArray.add(result);
			    }
			    
			    this.storage.performIOAction(Storage.WRITE_ACTION, documentArray);
			    this.storage.updateGrid();

			    startIndex += max;
			}
		    
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}		
		
		if (this.stop) {
			this.logger.debug("Thread killed.");
            return;
        }
		
		this.logger.debug("Thread ended.");
    }
	
	public void setQueryString(String queryString) {
		this.queryString = queryString;
	}
	
	public String getQueryString() {
		return this.queryString;
	}
	
	public void setCount(int count) {
		this.count = count;
	}
	
	public int getCount() {
		return this.count;
	}
	
	public void setStorage(Storage storage) {
		this.storage = storage;
	}	
	
	public Storage getStorage() {
		return this.storage;
	}

	public WebContext getWctx() {
		return wctx;
	}

	public void setWctx(WebContext wctx) {
		this.wctx = wctx;
	}
}
